package tech.mhuang.pacebox.springboot.autoconfiguration.trace.rest;

import io.opentracing.Tracer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import tech.mhuang.pacebox.springboot.autoconfiguration.ConfigConsts;
import tech.mhuang.pacebox.springboot.core.rest.MicroRestTemplate;
import tech.mhuang.pacebox.springboot.core.rest.SingleRestTemplate;

import java.util.Collections;
import java.util.regex.Pattern;

/**
 * restTemplate配置
 *
 * @author mhuang
 * @since 1.0.0
 */
@Configuration
@EnableConfigurationProperties(value = TraceRestTemplateProperties.class)
@ConditionalOnProperty(prefix = ConfigConsts.TRACE_REST, name = ConfigConsts.ENABLE, havingValue = ConfigConsts.TRUE, matchIfMissing = true)
public class TraceRestTemplateConfiguration {

    public final Tracer tracer;
    public final TraceRestTemplateProperties properties;

    public TraceRestTemplateConfiguration(Tracer tracer, TraceRestTemplateProperties properties) {
        this.tracer = tracer;
        this.properties = properties;
    }

    @Bean
    public TraceRestTemplateInterceptor traceRestTemplateInterceptor() {
        return new TraceRestTemplateInterceptor(tracer, Pattern.compile(properties.getSkipPattern()));
    }

    @Configuration
    @ConditionalOnBean(RestTemplate.class)
    class TraceDefRestTemplateConfiguration {
        public TraceDefRestTemplateConfiguration(RestTemplate restTemplate) {
            restTemplate.setInterceptors(Collections.singletonList(traceRestTemplateInterceptor()));
        }
    }

    @Configuration
    @ConditionalOnBean(SingleRestTemplate.class)
    class TraceSingeRestTemplateConfiguration {
        public TraceSingeRestTemplateConfiguration(SingleRestTemplate singleRestTemplate) {
            singleRestTemplate.setInterceptors(Collections.singletonList(traceRestTemplateInterceptor()));
        }
    }

    @Configuration
    @ConditionalOnBean(MicroRestTemplate.class)
    class TraceMicroRestTemplateConfiguration {
        public TraceMicroRestTemplateConfiguration(MicroRestTemplate microRestTemplate) {
            microRestTemplate.setInterceptors(Collections.singletonList(traceRestTemplateInterceptor()));
        }
    }
}